package com.android.lib.base.manager

import android.content.Context
import androidx.lifecycle.LifecycleOwner
import com.jeremyliao.liveeventbus.LiveEventBus
import com.android.lib.base.BuildConfig

object LiveBusManager {

    fun liveBusInit(context: Context? = null) {
        LiveEventBus.config()
            .autoClear(true)//配置在没有Observer关联的时候是否自动清除LiveEvent以释放内存（默认值false）
            //true：整个生命周期（从onCreate到onDestroy）都可以实时收到消息
            //false：激活状态（Started）可以实时收到消息，非激活状态（Stoped）无法实时收到消息，需等到Activity重新变成激活状态，方可收到消息
            .lifecycleObserverAlwaysActive(true)
            .enableLogger(com.android.lib.base.BuildConfig.DEBUG)
            //如果广播模式有问题，请手动传入Context，需要在application onCreate中配置
            .setContext(context)
    }

    fun observeString(owner: LifecycleOwner, key: String, l: (value: String) -> Unit) {
        LiveEventBus.get<String>(key).observe(owner) {
            l.invoke(it)
        }
    }

    fun observeInt(owner: LifecycleOwner, key: String, l: (value: Int) -> Unit) {
        LiveEventBus.get<Int>(key).observe(owner) {
            l.invoke(it)
        }
    }

    fun observeBoolean(owner: LifecycleOwner, key: String, l: (value: Boolean) -> Unit) {
        LiveEventBus.get<Boolean>(key).observe(owner) {
            l.invoke(it)
        }
    }


    fun postString(key: String, value: String) {
        LiveEventBus.get<String>(key).post(value)
    }

    fun postInt(key: String, value: Int) {
        LiveEventBus.get<Int>(key).post(value)
    }

    fun postBoolean(key: String, value: Boolean) {
        LiveEventBus.get<Boolean>(key).post(value)
    }

    fun postStringDelay(key: String, value: String, delay: Long = 2000) {
        LiveEventBus.get<String>(key).postDelay(value, delay)
    }

    fun postIntDelay(key: String, value: Int, delay: Long = 2000) {
        LiveEventBus.get<Int>(key).postDelay(value, delay)
    }

    fun postBooleanDelay(key: String, value: Boolean, delay: Long = 2000) {
        LiveEventBus.get<Boolean>(key).postDelay(value, delay)
    }


}